import axios from 'axios'
import {Message} from 'element-ui'
import store from '../store'
import {getToken,removeToken} from '../utils/auth'
import Qs from 'qs'


const getService = (opts = {}) => {
  // 创建axios实例

  let options = {
    baseURL: process.env.BASE_API, // api的base_url
    //timeout: 5000,
    withCredentials:true
  }


  if (opts.payload) {


  } else {


    options.transformRequest = [function (data) {

      data = Qs.stringify(data);
      return data;

    }]
  }

  //options.headers = {'token': store.getters.token};
  var service = axios.create(options);
  // console.log('options',options);
  service.interceptors.request.use(config => {


    if (!config.params) {
      config.params = {}
    }



    if (opts.payload) {

      config.data = parseData(config.data);

    }


    return config
  }, error => {
    //console.log(error)
    Promise.reject(error)
  })

  service.interceptors.response.use(

    response => {

      const res = response.data


      //console.log('res.statusCode',res.code)

      res.code === undefined ?res.code=0 : ""

      if(res.code == 500) {//为了登录时，输入用户名密码错误时给出错误提示
        //console.log('res',res);
        response.data.message = response.data.msg;
      }

      if(res.code == 401){

        removeToken()

      }else if (res.code != 0) {
        Message({
          message: res.message,
          type: 'error',
          duration: 5 * 1000
        })

        return Promise.reject(res)
      } else {
        //console.log('666',response.data)
        return response.data
      }

      return response.data;

    },
    error => {
      //console.log('err' + error)// for debug
      Message({
        message: error.message,
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(error)
    }
  )


  return service;

}


function parseData(data) {


  // if (typeof data == 'object') {
  //
  //   var str = JSON.stringify(data)
  //
  //   if (str.indexOf('.000Z') > 0) {
  //
  //     str = str.replace(/\.000Z/g, '').replace(/(\d+)T(\d+)/g, '$1 $2')
  //     return JSON.parse(str)
  //   }
  //
  //
  // }


  return data

}

export default {

  postPayload: (url, data) => {
    var fetch = getService({payload: true})

    return fetch({
      url: url,
      method: 'post',
      data: data
    })
  },
  post: (url, data) => {


    var fetch = getService()


    return fetch({
      url: url,
      method: 'post',
      data: data
    })
  },
  get: (url, params) => {
    var fetch = getService()


    return fetch({
      url: url,
      method: 'get',

      params: params
    })
  }
}
